<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: ot_gv.php 135 2013-09-22 07:30:55Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 135 $
* 	zuletzt geaendert von:	$Author: siekiera $
* 	Datum:					$Date: 2013-09-22 07:30:55 +0000 (Sun, 22 Sep 2013) $
*
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
*
* 	Copyright (c) since 2011 SEO:mercari
* --------------------------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     nextcommerce - www.nextcommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */

class ot_gv {
	var $title, $output, $db;

	function __construct() {
		global $price, $db;
		$this->code = 'ot_gv';
		$this->title = MODULE_ORDER_TOTAL_GV_TITLE;
		$this->header = MODULE_ORDER_TOTAL_GV_HEADER;
		$this->description = MODULE_ORDER_TOTAL_GV_DESCRIPTION;
		$this->user_prompt = MODULE_ORDER_TOTAL_GV_USER_PROMPT;
		$this->enabled = MODULE_ORDER_TOTAL_GV_STATUS == 'true' ? true : false;
		$this->sort_order = MODULE_ORDER_TOTAL_GV_SORT_ORDER;
		$this->include_shipping = MODULE_ORDER_TOTAL_GV_INC_SHIPPING;
		$this->include_tax = MODULE_ORDER_TOTAL_GV_INC_TAX;
		$this->calculate_tax = MODULE_ORDER_TOTAL_GV_CALC_TAX;
		$this->credit_tax = MODULE_ORDER_TOTAL_GV_CREDIT_TAX;
		$this->tax_class = MODULE_ORDER_TOTAL_GV_TAX_CLASS;
		$this->show_redeem_box = MODULE_ORDER_TOTAL_GV_REDEEM_BOX;
		$this->credit_class = true;
		$this->checkbox = '<input class="use_gv" type="checkbox" onclick="submitFunction();" name="'.'c'.$this->code.'" id="'.'c'.$this->code.'" /> '.$this->user_prompt;
		$this->output = array();
		$this->db = $db;
	}

	function process() {
		global $order, $price;
		if (isset($_SESSION['cot_gv']) && $_SESSION['cot_gv'] == true) {
			$order_total = $this->get_order_total();

			$od_amount = $this->calculate_credit($order_total);
			if ($this->calculate_tax != "None") {
				$tod_amount = $this->calculate_tax_deduction($order_total, $od_amount, $this->calculate_tax);
				$od_amount = $this->calculate_credit($order_total);
			}

			$this->deduction = $od_amount;

			$order->info['total'] = $order->info['total'] - $od_amount;

			if ($od_amount > 0) {
				$this->output[] = array ('title' => $this->title.':', 
										'text' => ' -'.trim($price->format($od_amount, true)), 
										'value' => $price->format($od_amount, false));
			}
		}
	}

	function selection_test() {
		if ($this->user_has_gv_account($_SESSION['customer_id']))
			return true;
		else
			return false;
	}

	function pre_confirmation_check($order_total) {
		global $order;
		$od_amount = 0;
		if (isset ($_SESSION['cot_gv']) && $_SESSION['cot_gv'] == true) {
			if ($this->include_tax == 'false')
				$order_total = $order_total - $order->info['tax'];

			if ($this->include_shipping == 'False')
				$order_total = $order_total - $order->info['shipping_cost'];

			$od_amount = $this->calculate_credit($order_total);

			if ($this->calculate_tax != "None") {
				$tod_amount = $this->calculate_tax_deduction($order_total, $od_amount, $this->calculate_tax);
				$od_amount = $this->calculate_credit($order_total) + $tod_amount;
			}
		}
		return $od_amount;
	}

	function use_credit_amount() {
		$_SESSION['cot_gv'] = false;
		if ($this->selection_test())
			$output_string .= $this->checkbox;
		
		return $output_string;
	}
	
	function getAmount($format = true) {
		global $price;
		if(isset($_SESSION['customer_id'])) {
			$gv_result = $this->db->db_query("SELECT amount FROM ".TABLE_COUPON_GV_CUSTOMER." WHERE customer_id = '".$_SESSION['customer_id']."'");
			if ($gv_result->fields['amount'] > 0)
				return $price->format($gv_result->fields['amount'], $format, 0, true);
			else
				return;
		}
	}
	
	function update_credit_account($i) {
		global $order, $insert_id, $REMOTE_ADDR;
		if (preg_match('/^GIFT/', addslashes($order->products[$i]['model']))) {
			$gv_order_amount = ($order->products[$i]['final_price']);
			if ($this->credit_tax == 'true')
				$gv_order_amount = $gv_order_amount * (100 + $order->products[$i]['tax']) / 100;

			$gv_order_amount = $gv_order_amount * 100 / 100;
			if (MODULE_ORDER_TOTAL_GV_QUEUE == 'false') {
				$gv_result = $this->db->db_query("SELECT amount from ".TABLE_COUPON_GV_CUSTOMER." WHERE customer_id = '".$_SESSION['customer_id']."'");
				$customer_gv = false;
				$total_gv_amount = 0;
				if ($gv_result->_numOfRows) {
					$total_gv_amount = $gv_result->fields['amount'];
					$customer_gv = true;
				}
				$total_gv_amount = $total_gv_amount + $gv_order_amount;
				if ($customer_gv)
					$gv_update = $this->db->db_query("UPDATE ".TABLE_COUPON_GV_CUSTOMER." set amount = '".$total_gv_amount."' WHERE customer_id = '".$_SESSION['customer_id']."'");
				else
					$gv_insert = $this->db->db_query("INSERT INTO ".TABLE_COUPON_GV_CUSTOMER." (customer_id, amount) VALUES ('".$_SESSION['customer_id']."', '".$total_gv_amount."')");

			} else {
				$gv_insert = $this->db->db_query("INSERT INTO ".TABLE_COUPON_GV_QUEUE." (customer_id, order_id, amount, date_created, ipaddr) VALUES ('".$_SESSION['customer_id']."', '".$insert_id."', '".$gv_order_amount."', NOW(), '".$REMOTE_ADDR."')");
			}
		}
	}

	function credit_selection() {
		global $currencies;
		$selection_string = '';
		$gv = $this->db->db_query("SELECT coupon_id, coupon_code FROM ".TABLE_COUPONS." WHERE coupon_type = 'G' and coupon_active='Y'");
		return $selection_string;
	}

	function apply_credit() {
		global $order, $coupon_no,$price;
		if (isset($_SESSION['cot_gv']) && $_SESSION['cot_gv'] == true) {
			$gv_result = $this->db->db_query("SELECT amount from ".TABLE_COUPON_GV_CUSTOMER." WHERE customer_id = '".$_SESSION['customer_id']."'");
			$gv_payment_amount = $this->deduction;
			$gv_amount = $gv_result->fields['amount'] - $price->RemoveCurr($gv_payment_amount);
			$gv_amount = str_replace(",", ".", $gv_amount);
			$gv_update = $this->db->db_query("UPDATE ".TABLE_COUPON_GV_CUSTOMER." set amount = '".$gv_amount."' WHERE customer_id = '".$_SESSION['customer_id']."'");
		}
		return $gv_payment_amount;
	}

	function collect_posts() {
		global $price, $coupon_no, $REMOTE_ADDR;

		if ($_POST['gv_redeem_code']) {
			$gv_result = $this->db->db_query("SELECT coupon_id, coupon_type, coupon_amount, coupon_code FROM ".TABLE_COUPONS." WHERE coupon_code = '".$_POST['gv_redeem_code']."'");
			$this->gv_code = $gv_result->fields['coupon_code'];
			if ($gv_result->_numOfRows) {
				$redeem = $this->db->db_query("SELECT * FROM ".TABLE_COUPON_REDEEM_TRACK." WHERE coupon_id = '".$gv_result->fields['coupon_id']."'");
				if ($redeem->_numOfRows && ($gv_result->fields['coupon_type'] == 'G')) {
					$_SESSION['error_message'] = urlencode(ERROR_NO_INVALID_REDEEM_GV);
					redirect(href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL'));
				}
			}
			if ($gv_result->fields['coupon_type'] == 'G') {
				$gv_amount = $gv_result->fields['coupon_amount'];
				$gv_amount_result = $this->db->db_query("SELECT amount FROM ".TABLE_COUPON_GV_CUSTOMER." WHERE customer_id = '".$_SESSION['customer_id']."'");
				$customer_gv = false;
				$total_gv_amount = $gv_amount;
				if ($gv_amount_result->_numOfRows) {
					$total_gv_amount = $gv_amount_result->fields['amount'] + $gv_amount;
					$customer_gv = true;
				}
				$gv_update = $this->db->db_query("UPDATE ".TABLE_COUPONS." SET coupon_active = 'N' WHERE coupon_id = '".$gv_result->fields['coupon_id']."'");
				$gv_redeem = $this->db->db_query("INSERT INTO  ".TABLE_COUPON_REDEEM_TRACK." (coupon_id, customer_id, redeem_date, redeem_ip) VALUES ('".$gv_result->fields['coupon_id']."', '".$SESSION['customer_id']."', now(),'".$REMOTE_ADDR."')");
				if ($customer_gv)
					$gv_update = $this->db->db_query("UPDATE ".TABLE_COUPON_GV_CUSTOMER." SET amount = '".$total_gv_amount."' WHERE customer_id = '".$_SESSION['customer_id']."'");
				else
					$gv_insert = $this->db->db_query("INSERT INTO ".TABLE_COUPON_GV_CUSTOMER." (customer_id, amount) VALUES ('".$_SESSION['customer_id']."', '".$total_gv_amount."')");
			}
		}
		if ($_POST['submit_redeem_x'] && $gv_result->fields['coupon_type'] == 'G') {
			$_SESSION['error_message'] = urlencode(ERROR_NO_REDEEM_CODE);
			redirect(href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL'));
		}
	}

	function calculate_credit($amount) {
		global $order;
		require_once(DIR_FS_INC.'inc.get_currencies_values.php');
		$gv_result = $this->db->db_query("SELECT amount FROM ".TABLE_COUPON_GV_CUSTOMER." WHERE customer_id = '".$_SESSION['customer_id']."'");
		$gv_payment_amount = $gv_result->fields['amount'];
		$gv_amount = $gv_payment_amount;
		$save_total_cost = $amount;
		$full_cost = $save_total_cost - $gv_payment_amount;
		if ($full_cost <= 0) {
			$full_cost = 0;
			$gv_payment_amount = $save_total_cost;
		}
		$t_gm_currency_array = array();
		$t_gm_currency_array = get_currencies_values($_SESSION['currency']);
		if(!empty($t_gm_currency_array['value'])) {
			$gv_payment_amount *= (double)$t_gm_currency_array['value'];
			$gv_payment_amount = round($gv_payment_amount, 2);
		}
		return $gv_payment_amount;
	}

	function calculate_tax_deduction($amount, $od_amount, $method) {
		global $order;
		switch ($method) {
			case 'Standard' :
				$ratio1 = number_format((double)$od_amount / $amount, 2);
				$tod_amount = 0;
				reset($order->info['tax_groups']);
				while (list ($key, $value) = each($order->info['tax_groups'])) {
					$tax_rate = get_tax_rate_from_desc($key);
					$total_net += $tax_rate * $order->info['tax_groups'][$key];
				}
				if ($od_amount > $total_net)
					$od_amount = $total_net;
				reset($order->info['tax_groups']);
				while (list ($key, $value) = each($order->info['tax_groups'])) {
					$tax_rate = get_tax_rate_from_desc($key);
					$net = $tax_rate * $order->info['tax_groups'][$key];
					if ($net > 0) {
						$god_amount = $order->info['tax_groups'][$key] * $ratio1;
						$tod_amount += $god_amount;
						$order->info['tax_groups'][$key] = $order->info['tax_groups'][$key] - $god_amount;
					}
				}
				$order->info['tax'] -= $tod_amount;
				$order->info['total'] -= $tod_amount;
				break;
			case 'Credit Note' :
				$tax_rate = get_tax_rate($this->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
				$tax_desc = get_tax_description($this->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
				$tod_amount = $this->deduction / (100 + $tax_rate) * $tax_rate;
				$order->info['tax_groups'][$tax_desc] -= $tod_amount;
				break;
			default :
				}
		return $tod_amount;
	}

	function user_has_gv_account($c_id) {
		$gv_result = $this->db->db_query("SELECT amount from ".TABLE_COUPON_GV_CUSTOMER." WHERE customer_id = '".(int)$c_id."'");
		if ($gv_result->_numOfRows != 0) {
			if ($gv_result->fields['amount'] > 0) {
				return true;
			}
		}
		return false;
	}

	function get_order_total() {
		global $order;
		if ($_SESSION['customers_status']['customers_status_show_price_tax'] != 0)
			$order_total = $order->info['total'];
		if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1)
			$order_total = $order->info['tax'] + $order->info['total'];
		if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 0)
			$order_total = $order->info['total'];
		if ($this->include_tax == 'false')
			$order_total = $order_total - $order->info['tax'];
		if ($this->include_shipping == 'False')
			$order_total = $order_total - $order->info['shipping_cost'];
		return $order_total;
	}

	function check() {
		if (!isset ($this->_check)) {
			$check = $this->db->db_query("SELECT configuration_value from ".TABLE_CONFIGURATION." WHERE configuration_key = 'MODULE_ORDER_TOTAL_GV_STATUS'");
			$this->_check = $check->_numOfRows;
		}

		return $this->_check;
	}

	function keys() {
		return array ('MODULE_ORDER_TOTAL_GV_STATUS', 'MODULE_ORDER_TOTAL_GV_SORT_ORDER', 'MODULE_ORDER_TOTAL_GV_QUEUE', 'MODULE_ORDER_TOTAL_GV_INC_SHIPPING', 'MODULE_ORDER_TOTAL_GV_INC_TAX', 'MODULE_ORDER_TOTAL_GV_CALC_TAX', 'MODULE_ORDER_TOTAL_GV_TAX_CLASS', 'MODULE_ORDER_TOTAL_GV_CREDIT_TAX');
	}

	function install() {
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) VALUES ('', 'MODULE_ORDER_TOTAL_GV_STATUS', 'true', '6', '1','cfg_select_option(array(\'true\', \'false\'), ', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, date_added) VALUES ('', 'MODULE_ORDER_TOTAL_GV_SORT_ORDER', '11', '6', '2', NOW())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) VALUES ('', 'MODULE_ORDER_TOTAL_GV_QUEUE', 'true', '6', '3','cfg_select_option(array(\'true\', \'false\'), ', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function ,date_added) VALUES ('', 'MODULE_ORDER_TOTAL_GV_INC_SHIPPING', 'true', '6', '5', 'cfg_select_option(array(\'true\', \'false\'), ', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function ,date_added) VALUES ('', 'MODULE_ORDER_TOTAL_GV_INC_TAX', 'true', '6', '6','cfg_select_option(array(\'true\', \'false\'), ', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function ,date_added) VALUES ('', 'MODULE_ORDER_TOTAL_GV_CALC_TAX', 'Standard', '6', '7','cfg_select_option(array(\'None\', \'Standard\', \'Credit Note\'), ', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, use_function, set_function, date_added) VALUES ('', 'MODULE_ORDER_TOTAL_GV_TAX_CLASS', '0', '6', '0', 'get_tax_class_title', 'cfg_pull_down_tax_classes(', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function ,date_added) VALUES ('', 'MODULE_ORDER_TOTAL_GV_CREDIT_TAX', 'false', '6', '8','cfg_select_option(array(\'true\', \'false\'), ', now())");
	}

	function remove() {
		$this->db->db_query("DELETE FROM ".TABLE_CONFIGURATION." WHERE configuration_key in ('".implode("', '", $this->keys())."')");
	}
}
?>